

name can hold the value of John Smith. Several rules need to be considered when declaring variable names. For starters, a variable name cannot begin with a number.2name = incorrect #incorrectname = correct #correctschool is not the same as School.print(name), the output will be john.260.var1 and var2 by converting var1 to an integer using the int() function. The following code will execute successfully.Make sure that the variable stores a value that can be converted to an integer before using the int() method.
True and False. In other words, something can either be true or false. We declare these values, as shown below. Please note that Python is case sensitive.bool() method can help convert a value to a boolean. The code snippets below showcase how a bool() function can be used.bool() function returns False when there are no parameters.[] to define a list.students list has an index. By default, the first index is 0. So the item at index [0] is john, while the value at index 1 is Mary Thomas. A list of integers will look as follows.student_marks list, we use the append function.Guardian Angel at the end of the student_marks list.len(student_marks) to determine the length of the list. We use the remove() function to delete something from the list. For instance, we can remove 90 from the student_mark list as shown below.-1 in the above student_marks list is "Guardian Angel". The second last element 78 has an index of -2.def keyword to declare a function. An example of a python method is shown below.success when it’s invoked. We can also pass data to a method, perform some calculations, and return the results. This is demonstrated in the code snippet below.calculateTotal method takes in two parameters (chem, bio). The function then returns the sum of the two values. It is important to take note of the data types when passing parameters. For instance, the calculateTotal method will not work when we pass in a string as a parameter. This is because the program cannot sum up an integer and a string. As shown above, we can call the calculateTotal method directly from our print statement.return keyword ensures that the method returns a result after execution.Note that a function can also call another method. This is illustrated below.
for and while.for loop above will print every item in the student_list.Note that the while loop above will be executed indefinitely until isChecked is set to false. You can press ctrl+c to stop the loop.
class keyword. Other elements are then nested in the class. Here is an example of a Python class.init function.Farmer class, the self keyword represents an instance of an object. In other words, it allows us to access the different methods and attributes defined in the class.: and indented code, while javascript and others generally use {} and indented code.Brian Kernighan actually wrote the first “Hello, World!” program as part of the documentation for the BCPL programming language developed by Martin Richards.
>, >>>, or $ depending on what you are using. After the prompt, try typing a line of code.#. The computer ignores all text starting after the #.''' before it, and ''' at the end. Technically, this is not a comment but a string, but the computer still ignores it, so we will use it.var, let, or const to declare a variable in python. You simply go name = 'value'."". To convert between these two, you can put an int in a str() function, and a string in a int() function. There is also a less used one, called a float. Mainly, these are integers with decimals. Change them using the float() command., in the print function, you can put a + to combine the variables and string.+-/* These operators are the same in most languages, and allow for addition, subtraction, division, and multiplicaiton. Now, we can look at a few more complicated ones:%//**+=-=/=*= Research these if you want to find out more…i++; or anything.Fun Fact: The python language was named after Monty Python.
' and a " both indicate a string, but do not combine them![num:num].
The first number stands for how far in you go from the front, and the second stands for how far in you go from the back..strip()len().lower().upper().replace().split()input <modulename>. Do not add the .py extension to the file name. In this example , we will be using a python created module named random.<module>.<function>. For example:Pro Tip: Dofrom random import randintto not have to dorandom.randint(), justrandint()To import all functions from a module, you could dofrom random import *
while <expression>. Every time the loop runs, it evaluates if the expression is True. It it is, it runs the code, if not it continues outside of the loop. For example:elif statement:else:python3pythonprint(5*4), and it shows 20.5, with entries from 1 to 10.5 * 3. The second thing we can do, is to try and print the calculated value, in a manner similar to 5 * 3 = 15. Then, we could repeat what we just did, to print out all the entries of the 5 multiplication table. Let’s put it down a little more formally:5 * 3 and print result as 155 * 3 = 15 (15 is result of previous calculation)1 to 10)5 * 5 for example, and print 25 for us. How do we get it to do that? That’s what we would be looking at in this step.5 * 5. How do we do that?5 X 5.X’ is not a valid operator in Python.*’ operator .5 * 5, and you can see the result 25 being printed. Similarly, 5 * 6 gives us 30.5 + 6 gives a result of 11.5 - 6 leads to -1.10 / 2, gives an output of 5.0 . There is one interesting operator, **. Let’s try 10 ** 3. We ran this code, and the result we get is 1000. Yes you guessed right, the operator performs “to the power of”. “10 to the power of 3” is 10 * 10 * 10, or 1000.%, called “modulo”, which computes the remainder on integer division. If we do 10 % 3, what is the remainder when 10 is divided by 3? 3 * 3 is 9, and 10 - 9 is 1, which is what % returns in this case.5 * 5, 5 * 6 and 5 - 6 are all expressions. An expression is composed of operators and operands.5 * 6, the two values 5 and 6 are called operands, and the * operator operates on them.5 and 6 are literals, because those are constants which cannot be changed.5 + 5 + 5, which evaluates to 15. This is an expression which has three operands, and two + operators. You can even have expressions with different types of operators, such as in 5 + 5 * 5.24.60.24 * 60, which is 1440.24.60, and60 as well.24 * 60 * 60, or 86400.5 + 6 + 10 is an example of an expression. In this expression, 5, 6 and 10 are operands. The + here is the operator. You can have multiple operators in an expression. We also did mention that the operands, namely 10, 6 and 5, are literals. Their values will not change.5 $ 2. You’re right, it would throw a SyntaxError. When Python does not understand the code you type in, it reports an error. Here, the expression we’re typing is 5 $ 2, which does not make sense to Python, hence the SyntaxError.5+6+10, without any spaces between the operands, and the operators. What do you think will happen? Surprisingly, the Python Shell does calculate the value!5 + 6 + 10 is easier to read than 5+6+10, but does not make any difference to the Python compiler.5 / 2, which is “5 divided by 2”. What would be the output? 2.5.2 as the output. Note that even though both operands are integers, the result of the / operation is a floating point value, 2.5 . Python does what is expected by a programmer!5 + 5 * 6. What would be the result of this expression? Will it be 5 + 5 or 10, then 10 * 6, which is 60? Or, will it be 5 plus 5 * 6, which is 5 + 30, that’s 35?35.**, *, / and % have higher precedence, or priority.+ and - have a lower precedence.*, /, %, **} are evaluated before those involving operators from {+, -}5 - 2 * 2. What would be the result of this? Will it be 6, or 1? It’s 1, because * has a higher precedence than -. Thus 2 * 2 is 4, and 5 - 4 gives us 1.5 - 2, to give an output of 2. How do we change the operator precedence?(5 - 2) gets calculated first, and the final result of the expression is 6.5 - 2 * 2, where we know the result according to precedence, adding parentheses is good.SyntaxError for incorrect operators5 * 6 = 30 . But trying to do so, as we know it, gives us a SyntaxError. Clearly, there is a different way to print text, as compared to an expression.Hello. Typing in this piece of code directly on Python Shell also gives us an error.Hello is not really an expression."Hello" is typically called a string, and represents the text of letters 'H', 'e', 'l', 'l', 'o'. "Hello" is hence different from the number 5.print() function. Can you just say print Hello?print(Hello) work?"Hello" is a string."Hello" is a string? By putting it within double quotes.print ("Hello")print("Hello") finally results in "Hello" being printed out. To be able to print "Hello", the things we need to do are:print()."Hello", which is called a parameter or argument, to print().5 * 6 = 30. The most basic version would be something of this kind, print("5 * 6 = 30"). Here, we are passing the entire value in the form of a string.30 using the formula 5 * 6, but directly putting text 30 in here. That’s called hard-coding.print() function, that is used to print text in Python."5 * 6 = 30" on the console, by hard-coding values in a string5 * 6 = 30. It was not a perfect solution, because we hard-coded everything. we used an in-built function named print(), passed a string to it, and invoked the method.print("5 * 6"), as in the previous step. What does this code result in?"5 * 6".print(5 * 6),5 * 6 is an expression. What will be the output? 30.print() with an expression argument, it prints the value of the expression. However, when we pass something within double quotes, it becomes a piece of text, printed as-is." and "), or single-quotes (' and ') with text values.abs() (which stands for absolute value), a method that accepts a numeric value. You can use abs(10.5), passing 10.5 as a value to it, and it prints the absolute value of 10.abs() function will not work with a string, it only works with numeric values”.2 to the power of 5”. In Python, there’s an in-built function named pow(), which does just what we need. To pow(), you can pass two parameters and calculate the result. How do you do that?pow 2 5? No, not at all. This code does not work as well: pow(2 5). pow(2, 5) is the correct syntax.32 is printed.10 to the power of 3”. pow(10,3) is the alternative to saying 10 ** 3. This gives us 1000, similar to how pow() would.max() returns maximum in a set of numbers.min() function returns the minimum value.pow(2,5). So this would give me 32. Now, what if I say capital 'P' instead of small 'p' here? Pow(2,5) would lead to an error.print("Hello") displays the text "Hello". Inside a string, the text can be in any case. Hence, print("hello") displays "hello" ,with a small 'h'.print("hellO World"), it would print "hellO World", with a space in between. And if you do print("hellO World") with three spaces, it would print the same. In expressions, white-space does not affect the output.", in the code. If we were to do this: print("Hello""), what would happen? The compiler says error!" inside a string, use an escape sequence. In Python, the symbol '\' is used as an escape character. On using '\' adjacent to the ", it prints Hello" (notice the trailing "). We have used the '\' to escape the ", by forming an escape sequence \".'\' is to print a <NEWLINE>. If you want to print "Hello World", but with "Hello" on one line and "World" on the next, '\n' is the escape sequence to use.'\t', which prints a <TAB> in the output. When you do print("Hello\tWorld"), you can see the tab-space between "Hello" and "World".\\ . If you want to print a \ , then use the sequence \\ . You would see that it prints Hello\World . Think about what would happen if we put six \ . Yes you’re right! It would print this string: "\\\" .print("Hello'World"), and notice the output we get. In a similar way, the following code will be accepted and run by the Python system: print('Hello"World').print() function to display expressions and strings"5 * 6 = 30".30 with a computed value.format() method can be used to print formatted text.10 to be printed, but it’s actually printing VALUE.10 to be printed then?{, closed brace }, and and by putting the index of the value between them. Here, the value is the first parameter, and it’s index will be 0."VALUE {0}" is what we need.format() function, we pass three values: 10, 20 and 30.0.0. To print the second value, pass an index of 1."5 * 6 = 30", but without hard-coding. Instead of 30, we want the calculated value of 5 * 6."5 * 6 = 30" with "5 * 6 = {2}". 2 is the index of parameter value 5*6.5 * 6 with the right indices - {0} * {1}.print() in the first place, without changing the indexes! So, we can display results for 5 * 7 = 35 and 5 * 8 = 40. We are now able to print 5 * 6 = 30, 5 * 7 = 35, 5 * 8 = 40, and can do similar things for other table entries as well.format() function, and saw how to call it within print()format(), and change the parameters we pass without changing the code5 * 8, 5 * 9 and 5 * 10. However, within the call to format(), we are only referring to the values at index 0, index 1 and index 2. The values at indexes 3 and 4 are not used at all. What would happen when we run the code?2, we pass 4. What would happen?5 * 10 is the value at index 4format(). However, inside the call to print(), we continue to say {0} * {1} = {4}. So we are trying to print the value at index 4, but are only passing two values to the function format(). What do you think will happen?IndexError, which means :“you are asking me to fetch the value at index 4, but only passing in two values. How can I do what you want?”print(): {0} * {1} = {2}, and would pass in 2.5, 2, and 2.5 * 2 . Here, 2 is an integer value, but 2.5 is a floating point value. You can see that it prints 2.5 * 2 = 5.0. So this approach of formatting values with print(), works also with floating point data as well.format() works with? Yes, strings can join the party.print("My name is {0}".format("Ranga")). What would happen?0 will be replaced with the first parameter to format().format():print()print()5 multiplication table.5 * 1 = 5, and then changing the literals. To make it print 5 * 2 = 10, we are changing 1 to 2. Next, we are changing 2 to 3. How do we make it a little simpler, so that our effort is reduced?1 with index, and 5 * 1 with 5 * index, and try to run it?index = 2. What would happen?5 * 2 = 10.index = 3. What would happen?5 * 3 = 15.index has? Just type in index.index symbol we have used here, is what is called a variable.index referring to, can change over the duration of a program.index was referring to a value of 1. later, index was referring to a value of 3.1, execute the same statement with print() and format(), to get output 5 * 1 = 5. Next, Change the value of index to 2, and then print the same statement. Next, index = 3, and print the same statement again.print("{0} * {1} = {2}".format(5,index,5*index)), we are able to print different values. The value of index varies, but the code remains the same!a, b and c. Let’s initially give them some values, say a value of 5 to a, 6 to b and 7 to c.5 + 6 + 7 = 18, without using the literal values.a, b and c.print("5 + 6 + 7 = 18").print("{0} + {1} + {2} = {3}".format(a,b,c,a+b+c)).a, b and c. Let’s make a = 6 , b = 7 , and c = 8 . Execute same statement.format() functionprint(count), it does not know what count is. So it would throw an error, saying: “count is not defined, I have no idea what count is.”count = 4 where we are creating a variable named count for the first time, is called a variable definition.count and Count are not the same thing._ . count, _count are valid. 1count is invalid.i = 5.i is referring to. If we say j = i, what would happen?j would start referring to the same value that i is referring to. This statement is called an assignment.j = 2 * i.j refers to a value of 10= has a different meaning in programming compared to mathematics.j = i, it means j and i are equal.5 is a literal.num1 = 5 and num2 = 3. We would want to add these and create a fresh variable. Let’s say the name of the variable is sum.a, b and c with different values and calculate their sum.=) operatorformat() method to format and print values. Let’s see a better approach to printing values.f"".a, we can use {a} in the text.{a+b}.5 + 6 + 7 = 18, using formatted strings.5-table from 5 * 1 = 5 onward, until we reach to 5 * 10 = 50. The best solution we have right now, is shown below:index value gets updated?index = index + 1 to increment index value.for loop, we need to specify the range of values - 1 to 10 or 1 to 20, and so on. range() function helps us to specify a range of values.for loop is: for i in range(1, 10): .... Here, i is the name of the control variable. In Python, you need to put a colon, ‘:’, and in the next line give indentation.1 to 9.range(1, 10), 1 is inclusive and 10 is exclusive.The loop runs from 1 to the value before 10, which is 9.print(i) is called indentation. We’ll talk about indentation later, when we talk about puzzles related to the for loop.print() with a formatted string. Now we want to print this statement for different values of i.print(f"{i}") prints the value of i.5 * 1 = 5 to 5 * 10 = 50?print(f"5 * {i} = {5 * i}") prints a specific multiple of 5.for loop, but don’t give a : after the range() method, to close the first line. What would happen?: is mandatory within the for loop syntax.: and in the next line, use print(i) without space before it (without indentation).{ and closed brace } as delimiters in a for loop. However, Python uses indentation to identify which code is part of a for loop, and which is not. So if we are writing the body of a for loop, we must use indentation, and leave atleast a single <SPACE>.for loop?print(i) and print(2*i).:for loop, indentation on a new line is recommended.<SPACE>s for indentation, instead of just two. This would give clear indentation of the code.print() is part of the for loop.10, which are 1, 3, 5, 7 and 9. The range() function offers an interesting option.for i in range(1, 11, 2), we pass in a third argument, called a step. After each iteration, the value of i is increment by step.for loop, which lay emphasis on the following aspects of for:range() functionfor loop, we looked at a number of puzzles.1, we need to start with 2. Each time, i it would be incremented by 2, and 2 4 6 8 and 10 would be printed.range() function. We’d want go from 10, 9, 8, and so on up to 1.10. As we discussed earlier, the end value is exclusive. So to print from 10 to 1, we want to end one value which is 0. range(10, 0) seems to be what we need.10. Hence, we would give a step value of -1.10 even numbers in reverse.-21, 11, 5, … are all called literals because these are constant values. Their values don’t really change. _Consider 5 _ 4 _ 50`. This is an expression. `_`is an operator, and`5`, `4`and`50 are operands.i in i = 1, is called a variable. It can refer to different values, at different points in time.range() and print() are in-built Python functions.print(), is invoking a method. The other statement which we looked at earlier, was an assignment statement. index = index + 1 would evaluate index + 1, and have the index variable refer to that value.for loop was very simple. for var in range(1, 10) : ..., followed by statements you would want to execute in a loop, with indentation. For the sake of indentation we left four <SPACE>s in front of each statement inside the for loop.7 table, we need to change the value 7 used in the for loop, to 8. It’s simple, but still not as friendly as you would like.7 table, it would be awesome if could say print_multiplication_table, and give a value of 7 beside it, and it would do the rest:print_multiplication_table(8), could print the multiplication table for 8!"Hello World", twice.print().print_hello_world_twice.def followed by a space.print_hello_world_twice.().: (similar to what we used in a for loop).print("Hello World") are indented. So, they are part of the method body.print_hello_world_twice() defines a method, and it has certain code inside its body.print_hello_world_twice?()!print_hello_world_thrice(). It should print "Hello World" thrice to the output. Define this method, and also invoke it.print_your_progress(), and you’re able to execute its code."Statement 1", "Statement 2", "Statement 3" and "Statement 4" on different lines, using just one print statement. How can you do that?\n.def keyword.print_your_progress() represents a method call. The code inside the method is executed.print_hello_world_twice(), and this printed "Hello World" twice. In this step, let’s talk about method arguments, or parameters.print_hello_world_thrice(), which prints the message three times.print_hello_world(5), and it would print “Hello World” five times?5 which we are passing here is called an argument.no_of_times. If you have any experience with other programming languages, they generally need you to specify the parameter type. Something like This parameter is an integer/float/string, or other types. But Python does not require parameter type.print_hello_world() ?print_hello_world with a parameter, but not passing anything in here! Go ahead and pass a value”. Let’s pass in a value, such as 5.print_hello_world(5), you can see "Hello World" and 5 being printed. We are now able to define this method to accept a value, and print that value by invoking it. You can pass in any value, such as10, 100, or others."Hello World". Consider print_hello_world(5), it should still print "Hello World" 5 times. How do you do that?"Hello World" 10 times.print_hello_world(5) now prints "Hello World" 10 times.5 times. We need to make use of the parameter no_of_times inside the for loop as well.4 times only.5 times?no_of_times as a second parameter to range() is exclusive.5 times!7, the message is displayed 7 times.for loop is part of the method body. So we have extra indentation for it. The print is part of the for loop body. So guess what, even more indentation for that code.print_numbers(), that would print all successive integers from 1 to n.print_squares_of_numbers(), that prints squares of all successive integers from 1 to n.printNumbers(). This convention is popularly known as “Camel Case”._ to separate words in the method name, as in print_numbers().print_squares_of_numbers(). This would be very similar to print_numbers(), working with the same range. Only, we need to say print(i*i) .n is a parameter, because it’s used in the definition of print_squares_of_numbers.5, that value is called an argument.print_hello_world accepts one parameter and prints “Hello World” the specified number of times.Welcome To Python, a specified number of times. How do you do that?print_welcome_to_python(no_of_times) and print the necessary text inside.print_string(str, no_of_times) accepting a text parameter, in addition to no_of_times.print_string("Welcome to Python") and run it, we get an error! Python Shell says: “I need no_of_times to be present in here”.str and no_of_times in print_string(). By default, we want to always print "Hello World", and that too 5 times.def print_string(str = "Hello World", no_of_times=5). The rest of the method remains the same.print_string(), and "Hello World" is displayed 5 times.print_string("Welcome To Python"), what does it do? It prints "Welcome To Python", 5 times.print_string("Welcome to Python", 8), it would print that string 8 times.print_multiplication_table(), and pass in a parameter to it.7.print_multiplication_table() with arguments 8, 9,and so on, by simply changing the table arguemnt value.print_multiplication_table() method.range(). We want to say print_multiplication_table(7, 1, 6), to print the 7 table with entries from 1 to 6. How can you do that?start, and the end.print_multiplication_table(7) would give us entries from 7 * 1 = 7 to 7 * 10 = 70.for loop, or outside it, proper indentation would be sufficient. In this step, let’s explore indentation in depth. Let’s start by creating a simple method.print(5) is indented at the same level as for loop.print(5) is called only once. It is not part of the for loop.print(5) is indented the same way as print(i)print(5) is part of the for loop. It is executed 10 times.{...}, as in other programming languages.print_string(6)?6 is passed as the first parameter. 6 is matched to str, and the method prints 6 the default number of times, which is 5."Hello World", and print it 6 times.no_of_times = 6. no_of_times is a named parameter.There is no provision of doing something like this, in other languages like Java.
print_string(no_of_times=6):str gets a default value, and "Hello World" is printed 6 times.print_string(7, 8). what happens?7 is printed 8 times.print() method is quite flexible, you can pass a number as the first argument. You can even pass a float.print_string(7.5, "eight")?no_of_times is used inside the method… as an argument to range(). range() only accepts integers, nothing else. When you run the code with print_string(7.5, "eight"), we get an error.TypeError: ```no_of_times``` must be ```int```, not string.range() function expects that the no_of_times is an integer value.print_string, print_multiplication_table, and the like.1_print will not be accepted as a method name.for loop, as in:for is a keywordin is a keyworddef is a keyword.while, return, if, else, elif, and many more.product_of_two_numbers(), and let’s have parameters a and b that it accepts:product = product_of_two_numbers(1,2), is this allowed?product.product_of_two_numbers() method is not really returning anything back, to be used elsewhere.max() for example.max() with four parameters, as in maximum = max(1,2,3,4), the value 4 gets stored in maximum.maximum * 5, or we can print the value of maximum, or a similar calculation. This gives our programs a lot more flexibility.a*b, if this function could return a value, that would be quite useful.product and doing a return product.product_result = product_of_two_numbers(2, 3)180 degrees. So if I am passing 50 and 50, 50 plus 50 is 100. So some of three angles should be 180, so the third angle will be 180 - 100, which is 80.sum. We could directly return a + b + c.return expression as well. That expression gets evaluated, and the value gets returned back. You’d see that the result remains the same.print("Hello world"). Does it get any simpler than this?python first.pyHello World will be printed.python3 first.py. If you look at other languages like Java for example, there is a separate compilation phase and then an execution phase. But with Python, just this command does both compilation and execution.python3 first.py , the change is compiled and executed as well!bytecode is not standardized. Different implementations of Python have different byte code. There are about 80 Python implementations, like CPython and Jython.python3 first.py, it is both compiled and executed. An intermediate format called bytecode is created, which is not really standardized in Python. The bytecode is executed in a Python virtual machine.print("Hello World"), and save it.'Hello World'.number = 5 , value = 2.5, etc. The 5 here is an integer, and integers represent numbers, such as 1, 2, 6, -1 and -2. In Python, the class for this particular data type is int.type(5), you’d get 'int' as the output.class.class, and what is an object or an instance. For now, the most important thing for you to remember, is that behind every value, there is a class.2.5, which is a floating point value.type(2.5), what would you see? You would see it’s of type `float.float. If you do 5/2, the result is 2.5. If we were to do 4/2, even then it’s of type float.value1 - value2 returns 1.299999999999998. Why?floats to represent your values. Instead, use Decimal. More about it later.int and float.int and a float, is always a float.int and float.ints, among floats, and also between ints and floats.simple_interest, and pass three parameters: principal, interest and duration (in years). You also want to calculate the amount after the specific duration, and return it back. Call this method with a few example values.simple_interest with 10000, with an interest of 5 percent, for a duration of 5 years, the correct answer would be as follows: 10000 is the principal. In addition to 10000, you get the interest. The interest for one year is 10000 * 0.05, as the interest figure is in percentage.So that’s 500 a year, into 5 which is 2500. The result would be 12500, and this value should be printed.i = 1. i = i + 1. What would be the value of i after that?2. There is a shortcut way of doing the same thing, by using the += operator.i++. There is no provision in Python to use increment operators like ++, in either prefix or suffix mode, like ++i, or i++.number1 = 5 and number2 = 2. What could be the result of number1 / number2? You know it, it’s 2.5 .number1 // nummber2 truncates the value of 2.5, to 2.number1 // number2, can you also do this: number1 //= number2?5 ** 3 is 5 ‘to the power of’ 3, which is 5 * 5 * 5, or 125.pow(5, 3). We have an operator, as well as a method at our disposal.int value to a float, or a float to an int.5.6 is nearer to 6 than 5. You can use a function called round(), and here,round(5.6) gives the correct result 6.round() can also allows you to specify number of decimals in the result.int to float, by using the function float().bool data type.True, and “false” by False. It’s important to remember that it’s True with a capital 'T', and False with a capital 'F'.is_even indicates whether a number is even or not.i = 10. We want to find out if i > 15. What do you think is the result? False.bool values. We looked at > and <. Another operation which you can perform, is >=.== is the comparison operator. We are only comparing the value of i against 10, not changing its value.bool data typebool variables are useful handy while testing logical conditionsif statement.if condition, which is the simplest conditional in Python. Let’s look at an example.i has a value of 5. You want to print something, only if i has a value greater than 3. How do you do that?if is very simple: if followed by a condition; with the condition you want to check. It looks like: if i>3: ... You need to indent the body of the if with <SPACE>s as usual.i has a value of 2. What would happen if we execute the same code again?i , either the statement is executed, or it’s not. That’s what an if helps us to do.if, is the body of code under the if is executed only when this condition is True. If this condition is not True, that code is not executed at all.a = 5, and b = 7. We want to compare them, and predict if a is greater that b .if statement, the simplest Python conditionalif helps in implementing conditional program logica = 1, b = 2 , c = 3 and d = 5. we want to find out, if a + b is greater than c + d.angle1 = 30, angle2 = 20 and angle3 = 60. You want to find out if these three angles actually form a valid triangle. You know that the sum of the angles of a triangle is always 180 degrees.%.bool values. These operators are called logical operators - and, or , not and ^ (xor).True, and the other False, and we want to play around with them.and returns true only when both operands are True.or returns true when atleast one of the operands is True.not returns negation.^ operator, is True when operands have different boolean values.and, or, not and ^True, and when False.i has a value of 10, and j has a value of 15. You want to find out if both i and j are even. How do you do that?i and j is even, we can use the or operator.if(True ^ False): print("Message")^ - message will get printed if the operands are different.True? No message is printed.^ in situations, where you’d want one of the operands to be True, and the other to be False.x = 5, and you want to check if not x == 6: print("This"). What will be the result of running this code?if x != 6 : print("This").int() is a conversion function, which when given say a float value, returns an int value. Consider int(True), what would happen?int(True) returns 1. int(False) returns 0.True.0 is the only integer value which is considered to be False.x = -6, and execute if x: print("something") what do you think will happen?"something" will be printed.bool(), to convert int to a bool value.bool(6) returns Truebool(-6) returns Truebool(0) returns False.bool(0), all the other results would be True.bool() and int() to convert between boolean and integer dataif statement: else and elif. Let’s start with else.i has a value of 2. Let’s try to print a message "i is even" if i is an even number. Otherwise, print "i is odd".if i % 2 == 0 : print("i is even"). However if this condition is not True, we would want to print("i is odd"). How do we accomplish that?else clause provides an alternative code body to execute, if the if condition is False.elif.i has value of 3, and something totally different if i has a value of 4.if condition. How can that be done?elif clause comes into the picture. The code in elif is executed if the previous conditions are false and the current elif condition is true.if statement: else and elif.elif clauses and the final else clause provide alternative conditions to check, when earlier if conditions are true.if, else and elif.value = input()input() method with a text ‘prompt’, such as "Enter A Value: ". What we can initially do here, is print the value which was entered, back to the console, by print("you entered ", integer_value).print(type(value)).Test. It has a class of str.12. what would happen?str.int() function converts string to int. Let’s use it."Enter A Value: " is prompted, and we enter 15. And now, of it says "You entered 15", and the type it indicates to us, is int.1, subtract is 2, divide is 3, and multiply is 4.input() function that can read console inputinput() always returns what the user enters, as a stringinput(), to the data type we expect by invoking conversion functionsif, elif and else conditions.if, elif and else clauses.2.k has a value of 15, is it greater than 20? No! Execution goes to the elif, is k greater then 10? Yes. It prints 2 and goes out of the complete if-else block.if conditional, the if, elif and else clauses are all independent ones. Only one matching block is ever executed.if conditions in here : if l < 20: ... immediately followed byif l > 20: ... else: ....if is true. l<20 is printed.if is a separate statement. The condition is false. So. else gets executed. Therefore, "who am I" gets printed.if block is executed only if the first if is true.10 is printed.number = number + 10 is part of if block. It is not executed because the condition is false.number = number + 5 is not part of if. So, it gets executed.number = number + 5.5 is printed.number = number + 10 and number = number + 5 are part of if block. They are not executed because the condition is false.if, elif and elseif statementstr!or""` to delimit string values.type() method can be used to find type of a variable.str class provides a lot of utility methods.message.capitalize() does init caps. Only first character is changed to uppercase.'hello'.capitalize(). Isn’t that cool!str class, and we can directly call methods of that class on str objects.istitle() will return a True value.isdigit() checks if a string is a numeric value.isalpha() checks if a string only contains alphabets.isalnum() checks if a string only contains alphabets and/or numerals.endswith is self explanatory.startswith is self explanatory as well.find method returns if a piece of text is present in another string. Returns the first match index.-1 is returned, if you’re searching for something which is not present in the string.'Ello' with a capital 'E' ,you’ll not be able to find it. Search is case sensitive.str converts boolean value to a text value.bool returns True for everything except empty string.int('45.56'), you can see that it throws an error. It says “I cannot convert this to an int, as 45.56 is an invalid integer”.int indicating the numeric system - 16 for Hexa decimal, 8 for Octal etc. Default is 10 - Decimal.int, bool and float values, and we looked at how to convert them to string, and how to convert strings back to these specific types.message = 'Hello', and we’re saying message.upper(). But what does it do? It prints 'HELLO', with all characters in uppercase. Well, what would happen if you do print(message)? It says 'Hello'.message.upper(), a new string is created, and it is returned back. Original string remained unchanged. This is called immutability.message = message.upper()”.message get changed? It prints 'HELLO', with all caps.message change? Does this prove that strings are mutable?message = 'Hello'str class with a values 'Hello'.message'Hello' is stored into message'Hello' in memory is A, then the value stored in message is A. message is called a reference.message = message.upper()?'HELLO' at a different location B.B is stored into message variable.A has not changed and cannot be changed for str variables. Hence ‘str’ objects are immutable.'Hello World' for example, is text data, and we stored it in message. This is called a string.char data type, to store a single character ch, in which 'h' is one character. But in Python, there is no separate data type to store single characters.message. The way you can access the first character of a string is by saying message[0].type(message[0]) and type(message) print the same type str. No difference.class, str.message[100] throws an IndexError.for ch in message: print(ch).string modulestring module.module into your program.string. and press , it would show the different things which are part of the string module.in operation on a string, checks if a given string.str module of Python.str ModuleA to Z.string module. We did the string module, and we saw that string module contained a number of things.string.ascii_uppercase, you have string.ascii_lowercase.'aeiou' is a consonant. The simplest way of doing this is to say consonant_string = 'bcdfghj...' and so on. Looks like a very long solution? There is an easier way out.string_example, and this is contains an English sentence. 'This is a great thing.''This', 'is', 'a', 'great' and 'thing' on individual lines.string_example. <TAB>. There are a huge list of methods, which would come up if you do that.split() method.split_lines() method looks for a '\n', and it divides the string based on it. If you have a string which contains newlines, and you would want to divide it into a number of strings with each line as a new element, the method you can use is split_lines().+ operator between two different types. + with two strings is concatenation. + with two numbers is addition.'1' * 20, What do you think will be the output?number, the string value is concatenated number times.str = 'test', and you have another string to with a value str1 = 'test1'.== operator.+*== operator to compare stringsfor loop, and the while loop.for loop helps us to loop around the same set of code statements, many times over.for loop is very simple.for i in range(1, 11): print(i).1 to 10.range() function, the second parameter is exclusive. We are actually looping from 1 to 10, and this piece of code, print(i), is being executed for different values of i.for loop can also be used to loop round the characters in a string.for loop can be used to loop around all the words in a given sentence.for loop can be used to loop around a specific list of values.for loopfor loop.is_prime(), which accepts an integer value as parameter, and returns whether it’s a prime. (Hint: A prime number is something which is only divisible by 1 and itself).5 is only divisible by 1 and 5. It is not divisible by any other number. Same is the case with 7 and 11.6 is divisible by 1, 2, 3 and 6. So it’s not a prime number.1. Hint: If I would want to find that the sum up to 6. what’s needed is 1 + 2 + 3 + 4 + 5 + 6.15. The divisors of 15 are 1, 3, 5 and 15. So I would want to calculate 1 + 3 + 5 + 15, and return that value.5, we would want to print the number triangle of these kind:for loop. We also test our skills, with creating method and executing them, in our IDE.is_prime() method, in a file named for_exercises.int parameter, and find out if it is prime, or not.1 and itself. If we are passed in a value of 5, you want to see if it’s divisible by any of 2, 3 or 4.for loop. We can structure it like this: for divisor in range(1, number): .... We would not want to divide it with 1, but start with 2 instead, and go up to number-1, which is 4.number is divisible by divisor?% operator. If number is divisible by divisor we return False.2, 3 and 4, but number was not divisible by all of them. In that case, number would be prime, and we can safely return True.1, the rules are a little different, as it is neither a prime or composite. We will add an if condition to check if the number is 1. if(number < 2):if condition is called a guard check or a boundary check, to make sure that you are processing only the right input. If number has a value less than 2, do nothing. OK, it’s not a prime.is_prime() exercise. In this step, let’s look at an implementation of sum_up_to_n(). Here is the entire code for this exercise:1, up to the input integer n.sum_of_divisors.sum_of_divisors() is very similar to is_prime().15, and if it’s dividing 15, with the remainder of 0, then you need to add that up.print_a_number_triangle.5, the output needs to be:1 2 3 4 5 first, and then we would look at how to print the rest of the output. Lets proceed with defining this method.def print_a_number_triangle(number): ... that takes a number as an input. You want to print a sequence of integers starting from 1, up to that specific number. How can you do that? Let’s try this: for i in range(1,number+1): print(i) What would happen? Let’s call print_a_number_triangle(5) now. It prints:<SPACE> instead. Call print() like this instead: for i in range(1,number+1): print(i, end=" ").1 2 3 4 5loop within a loop.1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5print("\n"), so we have a new line at the end of each outer loop iteration.1 in first line, upto 2 in second line and so on.j.number+1, let’s say j + 1.j has a value of 1, for will print from 1 to 1. When j has a value of 2, print from 1 to 2, literally printing 1 2. When j has a value of 3, I’ll print from 1 to 3. Let’s try this and see what would happen.while loop.for loop, we can specify the range of our iteration, by using the range() function.while loop, we specify a logical condition. While the condition is true, loop continues running.if statement.while loop.i has a value of 0, and we then do: while i < 5: print(i).0 again, and again. Let’s do a <CTRL-C> or <COMMAND-C> to interrupt this.i is 0, and the condition i < 5 is True, and print(i) is executed. Next iteration, it checks the condition, it is True, and 0 is printed. This continues to happen. What’s happening is an infinite loop.while loop, is to increment the value of i. We need to say something like i = i + 1.i initially had a value of 0. First the condition is checked. It’s True, so 0 is printed and then the value of i is incremented to 1.i is still less than 5, so the loop continues to execute, and this happens until 4 is printed. i again gets incremented to 4 + 1, or 5.i < 5. This is now False. Control goes out of the while loop, and terminates it.while, control flow is just based on a condition. As long as the condition is True, we keep executing the code. An important thing to remember, is to make sure the control variable is updated.for loop is much simpler to code than a while. With while, we have to write an expression statement, to increment the value.while loop in Pythonwhile, and a for loopwhile loop. In this step, let’s look at a couple of exercises using the while loop.print_squares_upto_limit(30): We need to print all the squares of numbers, up to a limit of 30. The output needs to be 1 4 9 16 25.print_cubes_upto_limit(30): We need to print all the cubes of numbers, up to a limit of 30.The output needs to be 1 8 27.while condition should now be i*i*i < 30.for loop? It would’ve been a little more difficult.for loop when we know how many times the loop will be executed is clear at the start.while is a better option.if statement to implement a solution for this: